package com.js.core.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.js.core.dto.ArticleDto;
import com.js.core.entity.ArticleContent;
import com.js.core.entity.result.ResultBean;
import com.js.core.dto.AttitudeDto;
import com.js.core.entity.Article;
import com.js.core.entity.ArticleAttitude;
import com.js.core.entity.Collection;
import com.js.core.mapper.ArticleAttitudeMapper;
import com.js.core.mapper.ArticleContentMapper;
import com.js.core.mapper.ArticleMapper;
import com.js.core.service.ArticleService;
import com.js.core.service.CollectionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/***
 *
 * @author knight
 * @Auther: MuYun
 * @Date: 2024/7/24 18:01
 * @Description：服务层实现类
 *
 */
@Service
@Transactional
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private CollectionService collectionService;

    @Resource
    private ArticleAttitudeMapper articleAttitudeMapper;


    @Override
    public ResultBean look(AttitudeDto attitudeDto) {
        ResultBean resultBean=new ResultBean();
        // 使用悲观锁查询
        Article article = articleMapper.selectByIdWithLock(attitudeDto.getArticleId());
        if(ObjectUtil.isNull(article)){
            return resultBean.setMsg("查看失败，该文章或已被删除");
        }
        article.setClickNum(article.getClickNum() + 1);
        // 更新文章观看数量
        articleMapper.updateById(article);
        return resultBean.setMsg("查看成功");
    }

    @Override
    public ResultBean queryArticleAndContent() {
        ResultBean resultBean=new ResultBean();
        return resultBean.setData(articleMapper.queryArticleAndContent());
    }

    @Override
    public ResultBean saveOrPubish(ArticleDto articleDto) {
        ResultBean resultBean=new ResultBean();
        try {
            //如果没传id，则当前文章处于待创建状态
            if(StrUtil.isEmpty(articleDto.getId())){
                articleDto.setId(IdUtil.randomUUID().toLowerCase());
            }
            articleDto.setUpdateBy("superuser");
            articleDto.setUpdateTime(DateUtil.date());
            articleMapper.saveOrUpdateArt(articleDto);
            resultBean.setCode(ResultBean.CODE_SUCCESS).setMsg("成功").setData(articleDto);
        }catch (Exception e){
            log.error("插入失败:{}",e);
            resultBean.setCode(ResultBean.CODE_ERROR).setMsg("失败");
        }
        return resultBean;
    }

    @Override
    public ResultBean agree(AttitudeDto attitudeDto) {
        ResultBean resultBean=new ResultBean();
        if("agree".equals(attitudeDto.getType())){
            // 使用悲观锁查询
            Article article = articleMapper.selectByIdWithLock(attitudeDto.getArticleId());
            if(ObjectUtil.isNull(article)){
                return resultBean.setMsg("点赞失败，该文章或已被删除");
            }
            article.setAgreeNum(article.getAgreeNum() + 1);
            // 更新文章点赞数量
            articleMapper.updateById(article);
            //新增该用户对该文章的态度关系
            addAttitude(attitudeDto);
            attitudeDto.setType("dislike");
            clearAttitude(attitudeDto);//考虑到点踩后点赞的情况，会删除原有的点踩记录
        }else{//取消点赞情况
            attitudeDto.setType("agree");
            clearAttitude(attitudeDto);
        }
        return resultBean.setMsg("请求成功");
    }

    @Override
    public ResultBean dislike(AttitudeDto attitudeDto) {
        ResultBean resultBean=new ResultBean();
        // 使用悲观锁查询
        Article article = articleMapper.selectByIdWithLock(attitudeDto.getArticleId());
        if(ObjectUtil.isNull(article)){
            return resultBean.setMsg("点踩失败，该文章或已被删除");
        }
        if("afterDislike".equals(attitudeDto.getType())){//点赞后再点踩，会删除点赞态度的记录
            article.setAgreeNum(article.getAgreeNum() - 1);
            attitudeDto.setType("agree");
            clearAttitude(attitudeDto);
            attitudeDto.setType("dislike");//统一点踩和点赞后点踩的态度类型
        }
        //新增该用户对该文章的态度关系
        addAttitude(attitudeDto);
        // 更新文章点赞数量
        articleMapper.updateById(article);
        return resultBean.setMsg("请求成功");
    }

    @Override
    public ResultBean collect(AttitudeDto attitudeDto) {
        ResultBean resultBean=new ResultBean();
        if("collect".equals(attitudeDto.getType())){
            // 使用悲观锁查询
            Article article = articleMapper.selectByIdWithLock(attitudeDto.getArticleId());
            if(ObjectUtil.isNull(article)){
                return resultBean.setMsg("收藏失败，该文章或已被删除");
            }
            article.setAgreeNum(article.getAgreeNum() + 1);
            // 更新文章收藏数量
            articleMapper.updateById(article);
            Collection collection=new Collection();
            collection.setArticleId(article.getId());
            collection.setUserId("当前登录用户");
            collection.setCreateTime(DateUtil.date());
            collectionService.save(collection);
            //新增该用户对该文章的态度关系
            addAttitude(attitudeDto);
        }else {//取消收藏
            attitudeDto.setType("collect");
            clearAttitude(attitudeDto);
        }
        return resultBean.setMsg("请求成功");
    }

    @Override
    public ResultBean queryAttitude(ArticleAttitude attitude){
        ResultBean resultBean=new ResultBean();
        QueryWrapper<ArticleAttitude> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", attitude.getArticleId());
        queryWrapper.eq("user_id", "模拟当前登陆用户id");
        List<ArticleAttitude> articleAttitudes = articleAttitudeMapper.selectList(queryWrapper);
        return resultBean.setData(articleAttitudes);
    }

    /**
     * @description  新增用户对文章的态度记录
     * @author  mazp
     * @date    2025/7/11 17:51
     * @param	attitudeDto
     * @return  void
    */
    public void addAttitude(AttitudeDto attitudeDto){
        ArticleAttitude articleAttitude=new ArticleAttitude();
        articleAttitude.setArticleId(attitudeDto.getArticleId());
        articleAttitude.setUserId("模拟当前登陆用户id");
        articleAttitude.setType(attitudeDto.getType());
        articleAttitude.setCreateTime(DateUtil.date());
        articleAttitudeMapper.insert(articleAttitude);
    }

    /**
     * @description  删除用户对文章的态度记录（针对取消点赞/取消收藏/点赞后点踩的情况）
     * @author  mazp
     * @date    2025/7/11 17:51
     * @param	attitudeDto
     * @return  void
    */
    public void clearAttitude(AttitudeDto attitudeDto) {
        QueryWrapper<ArticleAttitude> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("article_id", attitudeDto.getArticleId());
        queryWrapper.eq("type", attitudeDto.getType());
        queryWrapper.eq("user_id", "模拟当前登陆用户id");
        articleAttitudeMapper.delete(queryWrapper);
    }
}
